<template>
	<view class="grab-details">
		<!-- #ifdef APP-PLUS -->
		<top-set></top-set>
		<tab-top title="抢单" fixed="true"></tab-top>
		<!-- #endif -->
		<view class="choose_order">
			<view class="message">
				您目前最多可再抢{{ccount}}单!
			</view>
			<view class="list" v-if="have == '1'">
				<view class="item" v-for="(item1, index1) in list" :key="index1">
					<view class="time">
						<view class="icon">
							<image src="/static/icon/time.png" mode=""></image>
						</view>
						<view class="text">预约{{item1.subscribe_time}}到店  <text style="color: #f93735;margin-left: 5upx;"> {{ item1.time_stamp}}</text></view>
					</view>
					<view class="row " :class="[(index2 + 1) == item1.orderList.length && ( index1 + 1) == list.length?'':'line-row']"
					 v-for="(item2, index2) in item1.orderList" :key="index2">
						<view class="col" v-for="(item3, index3) in item2" :key="index3" @tap="activeRoom(item3)">
							<view class="icon">
								<image :src="item3.active?'/static/order/item2.png':'/static/order/item1.png'" mode=""></image>
							</view>

							<!-- #3595f9; -->
							<view class="title" :class="[item3.active?'title_active':'']">{{item3.room.room_no + item3.room.room_type}}</view>
						</view>

					</view>
				</view>
			</view>
		</view>
		<view class="choose_home">
			<view class="box">
				<view class="choose_five selection" @tap="electionRoom('5')">
					<view class="choose_icon " :class="[checked == '5'?'choose_icon_checked':'']">
						<image src="/static/icon/dui.png" mode=""></image>
					</view>
					<view class="choose_text">选五间</view>
				</view>
				<view class="choose_ten selection" @tap="electionRoom('10')">
					<view class="choose_icon" :class="[checked == '10'?'choose_icon_checked':'']">
						<image src="/static/icon/dui.png" mode=""></image>
					</view>
					<view class="choose_text">选十间</view>
				</view>
				<view class="choose_all selection" @tap="electionRoom('all')">
					<view class="choose_icon" :class="[checked == 'all'?'choose_icon_checked':'']">
						<image src="/static/icon/dui.png" mode=""></image>
					</view>
					<view class="choose_text">全选</view>
				</view>
			</view>
		</view>

		<view class="tips">
			<view class="title">
				温馨提示:
			</view>
			<view class="line">
				1. 房间类型说明：房间号后面的字母代表着房间的类型，B代表标间，D代表大床房，T代表套房；
			</view>
			<view class="line">
				2. 本平台服务标准：标间10元/间，大床房10元/间，套房15元/间；
			</view>
			<view class="line">
				3. 接单成功后，您可以在30分钟内取消订单；
			</view>
			<view class="line">
				4. 接单成功后,规定时间内未到店，店方有权无责取消订单；
			</view>
		</view>

		<view class="umap">
			<view class="hotel_info" @tap="openHotel">
				<view class="hotel_icon">
					<image :src="hotelInfo.hotel_logo" mode=""></image>
				</view>
				<view class="hotel_text">
					<view class="hotel_name">{{hotelInfo.name}}</view>
					<view class="hotel_start">
						{{hotelInfo.hotel_type.name || '经济型'}}
					</view>
				</view>
				<view class="hotel_back">
					<image src="/static/icon/right.png" mode=""></image>
				</view>
			</view>
			<view class="u_map">

				<!-- <map class="map"  :latitude="latitude" :longitude="longitude" scale="18" :markers="markers" > -->
					<view class="controls" @tap="openMap">
						<view class="controls-title">打扫地点</view>
						<view class="controls-content" >{{hotelAdress}}</view>
						<image class="controls-img" src="/static/icon/right.png"></image>
					</view>

				<!-- </map> -->	
					
					
				



			</view>


		</view>

		<view class="grab_button">
			<view class="grab_button_fixed">
				<view class="grab_button_btn" @tap="grab">
					立刻抢单
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import amapFile from '@/common/amap-wx.js';
	import moment from "moment";
	
	
	let id = '',
		roomData = [],
		lastActive,
		ccount,
		grabFlag = false;
	export default {
		onReady(){
			

			// const subNVue = uni.getSubNVueById('grab-map');
			// subNVue.show();  
			// subNVue.onMessage((res) => {  
			// 	const data = res.data;  
			// 	// 执行一些操作  
			// 	this.grab();
			// });

		},
		data() {
			return {
				have: "0",
				ccount:0,
				mapShow:false,
				title: 'map',
				hotImg: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1558332284730&di=336faecced1f491f34e6a72eb12463e4&imgtype=0&src=http%3A%2F%2Fpic36.photophoto.cn%2F20150829%2F0005018473589025_b.jpg',
				list: [{
					"orderList": [
						[{
							"id": "",
							"order_sn": "",
							"subscribe_time": 0,
							"roomtype": {
								"name": "",
								"sign": "",
								"price": ""
							},
							"room": {
								"id": "",
								"room_no": "",
								"room_type": "",
								"storey": ""
							},
							"active": false
						}],

					],
					"subscribe_time": 1558497600
				}],
				hotelInfo: {},
				hotelAdress:'',
				checked: '0', //5(选五间) 10(选十间) all(全选)
			}
		},
		onLoad(e) {
			id = e.id;

			
		},
		methods: {
			electionRoom(val) {

				let checkedNum = roomData.length;
				
				if(lastActive == val){
					console.log('重复点击')
					this.checked = '0';
					lastActive = this.checked;
					this.reverseCheck();
					console.log(roomData);
					return;
				}
				switch (val) {
					case '5':
						if (checkedNum >= ccount) {
							uni.showToast({
								icon: 'none',
								title: "最多可再抢"+ccount+"间"
							});
							return;
						}
						if(lastActive == '10' || lastActive == 'all' || checkedNum >= 5){
							this.reverseCheck();
							checkedNum = roomData.length;
						}
						/**
						 * 如果已经选中的房间加上还可以再选的房间的数量小于5 那么全选
						 */
						if(ccount + checkedNum < 5){
							this.multiCheck(ccount - checkedNum);
						}else{
							this.multiCheck(5 - checkedNum);
						}
						
						

						
						this.checked = val;
						break;
					case '10':
						if (checkedNum >= ccount) {
							uni.showToast({
								icon: 'none',
								title: "最多可再抢"+ccount+"间"
							});
							return;
						}
						if(lastActive == 'all' || checkedNum >= 10 || lastActive == '5'){
							this.reverseCheck();
							checkedNum = roomData.length;
						}
						/**
						 * 如果已经选中的房间加上还可以再选的房间的数量小于10间 那么全选
						 */
						if(ccount + checkedNum < 10){
							this.multiCheck(ccount - checkedNum);
						}else{
							this.multiCheck(10 - checkedNum);
						}
						console.log(checkedNum);
						
						this.checked = val;
						break;
					case 'all':
						if (checkedNum >= ccount) {
							uni.showToast({
								icon: 'none',
								title: "最多可再抢"+ccount+"间"
							});
							return;
						}
						this.multiCheck(ccount - checkedNum);
						this.checked = val;
						break;
					default:
						break;
				}
				lastActive = val;
				console.log(roomData);
				
			},
			/**
			 * 多选功能
			 */
			multiCheck(num) {
				let activeNum = 0;

				this.list.forEach((item1, index1) => {

					let arr1 = item1;
					console.log(arr1);


					item1.orderList.forEach((item3, index3) => {

						item3.forEach((item4, index4) => {

							if (activeNum < num) {

								if (!item4.active) {

									item4.active = true;
									roomData.push(item4);
									activeNum++;

								}

							}
						})

					})



				});

			},
			/**
			 * 反选
			 */
			reverseCheck(){
				// for (let i = 0; i < this.list.length; i++) {
				// 	for (let j = 0; j < this.list[i].orderList.length; j++) {
				// 		for (let k = 0; k < this.list[i].orderList[j].length; k++) {
				// 			this.list[i].orderList[j][k].active = false;
				// 		}
				// 	}
				// }
				// roomData = [];
				this.list.forEach((item1, index1) => {
				
				
					item1.orderList.forEach((item3, index3) => {
				
						item3.forEach((item4, index4) => {
				
								item4.active = false;
								roomData.pop();
						})
				
					})
				
				
					
				});
				
				
			},
			async grab() {
				if(grabFlag){
					
					return;
				}
				grabFlag = true;
				uni.showLoading();
				
				/**
				 * 整合数据为下个页面可用数据
				 */
				if (roomData.length <= 0) {
					uni.showToast({
						icon: 'none',
						title: '未选中房间'
					})
					grabFlag = false;
					return;
				}

				let obj = {
					count: roomData.length,
					price: 0,
					orderArray1: [],
					hotelInfo: this.hotelInfo
				};
				let arrId = [];
				roomData.forEach((v, i) => {
					let orderArray1 = {
						id:v.room.id,
						room: v.room.room_no + v.room.room_type,
						storey: v.room.storey,
						price:v.roomtype.price
					};
					// obj.price += v.roomtype.price * 1;
					obj.price = this.accAdd(obj.price * 1, v.roomtype.price * 1);
					obj.orderArray1.push(orderArray1);
				});
				
				
				


				let res = await this.addOrderStatus();
				
				
				if (res.data.status == 1) {
					
					if(res.data.data.past_order){
						uni.showToast({
							icon:'none',
							title:res.data.data.msg
						});
						let pastList =  res.data.data.past_order.list;
						console.log(pastList);
						// let pastList =  [{id: "9A4371A4_082C_18DB_5065_96212F0C", room: "O1016", storey: "1"}];
						pastList.forEach((item1,index1)=>{
							
							obj.orderArray1.forEach((item2,index2)=>{
									
									if(item1.room_id  == item2.id){
										obj.orderArray1.splice(index2,1);
										// obj.price -= item2.price;
										obj.price = this.accSub(obj.price * 1, item2.price * 1);
										obj.count--;
									}
									
							})
							
						});
						
					}else{
						
					}
					obj = JSON.stringify(obj);
					setTimeout(function(){
						grabFlag = false;
						uni.navigateTo({
							url: '/pages/cleaner/order/rush-complete?order=' + obj
						});
						try{
							uni.hideLoading();
						}catch(e){
							console.log(e);
							//TODO handle the exception
						} 
						
					},1000)
					
				} else {
					uni.showToast({
						icon: 'none',
						title: res.data.message
					})
					grabFlag = false;
				}
				

			},
			/**
			 * 获取信息
			 */
			getData() {

				return new Promise((res) => {
					this.req({
							url: 'both/grabSheetList',
							method: 'get',
							data:{
								hid:id,
								cid:this.isLogin().id
							}
						},
						(data) => {

							res(data);
						});
				});
			},
			/**
			 * 获取初始数据
			 */
			async getInitialData() {
				let res = await this.getData();
				this.list = this.filterDataLine(res.data.data.list);
				this.ccount = res.data.data.ccount;
				ccount = this.ccount;
				this.hotelInfo = res.data.data.hotel_info;
				this.hotelAdress = res.data.data.hotel_info.hotel_address;
				this.have = '1';
				
				// this.useMap();

				this.mapShow = true; //等待页面数据加载完成再渲染地图

				
				
			},
			/**
			 * 过滤数据为可用数据
			 */
			filterDataLine(arr) {


				let newArr = [];
				let timestamp = (new Date()).getTime();
				for (let i = 0; i < arr.length; i++) {
					let newObj = {
						orderList: [],
						subscribe_time: arr[i].subscribe_time ? moment(arr[i].subscribe_time * 1000).format('MM-DD HH:mm') : '',
						time_stamp:'' 
					};
					if(arr[i].subscribe_time*1000 - timestamp < 600000 && arr[i].subscribe_time*1000 >= timestamp){
						newObj.time_stamp = "(到店时间不足十分钟)"
					}

					for (let k = 0; k < arr[i].orderList.length; k++) {
						arr[i].orderList[k].active = false;
					}

					for (let j = 0; j < arr[i].orderList.length; j += 5) {
						newObj.orderList.push(arr[i].orderList.slice(j, j + 5));
					}
					newArr.push(newObj);
				}
				return newArr;
			},
			/**
			 * 选中房间
			 */
			activeRoom(item) {




				if (!item.active) {
					if (roomData.length >= ccount) {
						uni.showToast({
							icon: 'none',
							title: "最多可选"+ccount+"间房间"
						});
						return;
					}
					item.active = true;
					roomData.push(item);
				} else {
					item.active = false;

					for (let i = 0; i < roomData.length; i++) {
						if (roomData[i].id == item.id) {
							console.log(i);
							roomData.splice(i, 1);
						}
					}
				}
				
				if(lastActive != '0'){
					this.checked  = '0';
					lastActive = '0';
				}
				
				
				console.log(roomData);
			},
			/**
			 * 保洁抢单
			 */
			addOrderStatus() {
				// both/addOrderStatus
				let order_data_json = [];

				roomData.forEach((v, i) => {
					order_data_json.push(v.id);
				});
				order_data_json = JSON.stringify(order_data_json);

				return new Promise((res) => {
					this.req({
						url: 'both/addOrderStatus',
						data: {
							cid: this.isLogin().id,
							hid: this.hotelInfo.id,
							order_data: order_data_json
						}
					}, (data) => {
						console.log(data);
						res(data);
					});
				})
			},
			/**
			 * 绘制地图
			 */
			useMap() {
				var that = this;
				// this.amapPlugin = new amap.AMapWX({
				// 	key: '4145b1f386eff69d44630adaed44cd6c'
				// });
				var amapPlugin = new amapFile.AMapWX({
					key: '4145b1f386eff69d44630adaed44cd6c'
				});
				amapPlugin.getPoiAround({
					success: function(data) {
						//成功回调
						
						that.poisdatas = data.poisData;
						var markers_new = [];
						that.markers.forEach(function(item, index) {
							markers_new.push({
								id: item.id, //marker 序号
								width: item.width, //marker 宽度
								height: item.height, //marker 高度
								iconPath: item.iconPath, //marker 图标路径
								latitude: item.latitude, //marker  纬度
								longitude: item.longitude, //marker 经度
							})
						})
						that.markers = markers_new;

					},
					fail: function(info) {
						//失败回调
						console.log("info", info)
					}
				})



			},/**
			 * 打开地图
			 */
			openMap(){
				uni.openLocation({
					longitude: Number(this.hotelInfo.hotel_longitude),
					latitude: Number(this.hotelInfo.hotel_latitude),
					name: this.hotelInfo.name,
					address:this.hotelAdress
				});
				// this.mapNavigation(this.latitude,this.longitude,this.hotelInfo.name); 
			},
			/**
			 * 打开酒店页面
			 */
			openHotel(){
				uni.navigateTo({
					url: '/pages/cleaner/hotel/hotel?id=' + this.hotelInfo.id
				});
			},
			/**
			 * 监听数组变化
			 */
			monitorArrayChanges(arr,callbcak){
				const arrayProto = Array.prototype;
				const arrayMethods = Object.create(arrayProto);
				const newArrProto = [];
				[
				  'push',
				  'pop',
				  'shift',
				  'unshift',
				  'splice',
				  'sort',
				  'reverse'
				].forEach(method => {
				  let original = arrayMethods[method];

				  newArrProto[method] = function mutator() {
					
					original.apply(this, arguments);
					return callbcak(arr.length);  
				  }
				});
				arr.__proto__ = newArrProto;
				 
			}
		},
		mounted() {

		},
		computed: {

		},
		onShow() {
			roomData = [];
			grabFlag = false;
			// this.mapShow = false;
			this.checked = '0';
			lastActive = '0';
			this.getInitialData();
			this.monitorArrayChanges(roomData,(res)=>{
				console.log('数组变化后的长度'+res);
				this.ccount =  (ccount - res);
			});
		}
	}
</script>

<style lang="scss" scoped>
	.title_active {
		color: #3595f9 !important;
	}

	.grab-details>.choose_order {
		box-sizing: border-box;
		padding: 31upx 24upx 0 24upx;

		.message {
			height: 50upx;
			background-color: #ffffff;
			box-shadow: 0px 1upx 4upx 0px rgba(0, 0, 0, 0.2);
			border-radius: 8upx;
			font-size: 24upx;
			line-height: 50upx;
			color: #f93735;
			text-indent: 28upx;
		}

		.list {

			margin-top: 30upx;

			.item {
				width: 100%;
				padding-bottom: 43upx;
				height: auto;

				.time {
					line-height: 26upx;
					height: 26upx;

					.icon {
						width: 26upx;
						height: 26upx;
						float: left;

						image {
							float: left;
							width: 100%;
							height: 100%;
						}
					}

					.text {
						margin-left: 14upx;
						font-size: 26upx;
						color: #333333;
						float: left;
					}

				}

				.row {
					height: 127upx;
					width: 100%;
					box-sizing: border-box;
					position: relative;
					padding-left: 55upx;
					white-space: nowrap;

					.col {
						display: inline-block;
						width: 80upx;
						margin-right: calc((100% - 400upx) / 4);
						height: 100%;
						box-sizing: border-box;
						padding-top: 29upx;

						.icon {
							width: 48upx;
							height: 48upx;
							margin: 0 auto;

							image {
								float: left;
								width: 100%;
								height: 100%;
							}
						}

						.title {
							text-align: center;
							margin-top: 9upx;
							line-height: 1;
							color: #999999;
							font-size: 20upx;
						}
					}

					.col:nth-last-of-type(1) {
						margin-right: 0;
					}
				}

				.line-row:after {
					content: '';
					position: absolute;
					left: 55upx;
					bottom: 1upx;
					width: calc(100% - 55upx);
					height: 1px;
					background: #e5e5e5;
					transform: scaleY(0.5);
				}
			}
		}
	}

	.grab-details>.choose_home {
		height: 100upx;
		position: relative;
		box-sizing: border-box;
		padding: 37upx 24upx 34upx 24upx;
		background-color: #f8f8f8;

		.box {
			width: 100%;
			height: 100%;
			display: flex;
			justify-content: space-between;
			align-items: center;
			.choose_five{
				justify-content:flex-start;
			}
			.choose_ten{
				justify-content:center;
			}
			.choose_all{
				justify-content:flex-end;
			}
			.selection {
				width: 33.3333333333%;
				height: 100upx;

				display:flex;
				
				

				align-items:center;

				.choose_icon_checked {
					border: none !important;

					image {
						display: block !important;
					}
				}

				.choose_icon {
					float: left;
					width: 28upx;
					height: 28upx;
					border-radius: 50%;
					border: 1upx solid #999999;
					box-sizing: border-box;

					image {
						display: none;
						float: left;
						width: 28upx;
						height: 28upx;
					}
				}

				.choose_text {
					float: left;
					font-size: 24upx;
					line-height: 28upx;
					margin-left: 12upx;
				}

			}
		}
	}

	.grab-details>.tips {
		padding: 60upx 24upx 50upx 24upx;

		.title {
			font-size: 26upx;
			color: #999999;
			line-height: 1;
		}

		.line {
			margin-top: 25upx;
			color: #999999;
			font-size: 24upx;
			line-height: 38upx;
		}
	}

	.choose_home:after {
		position: absolute;
		left: 0;
		top: 0;
		height: 1upx;
		width: 100%;
		content: "";
		background: #e5e5e5;
	}

	.grab-details>.umap {
		width: 100%;

		.u_map {
			position: relative;
			width: 100%;
			height: 260upx;
		}

		

		.hotel_info {
			height: 100upx;
			width: 100%;
			box-sizing: border-box;
			padding: 0 24upx;
			position: relative;

			.hotel_icon {
				height: 100upx;
				width: 100upx;
				box-sizing: border-box;
				border: 2upx solid #999999;
				border-radius: 7upx;
				overflow: hidden;
				image {

					width: 96upx;
					height: 96upx;
					
				}

				float: left;
			}

			.hotel_text {
				float: left;
				margin-top: 12upx;
				margin-left: 34upx;

				.hotel_name {
					font-size: 32upx;
					color: #333333;
					line-height: 1;
				}

				.hotel_start {
					margin-top: 26upx;
					height: 24upx;
					font-size: 24upx;
					color: #333333;
					line-height: 1;
					.start_icon {
						height: 24upx;
						float: left;

						image {
							float: left;
							width: 22upx;
							height: 22upx;
							margin-right: 4upx;
						}
					}

					.start_text {
						float: left;
						font-size: 24upx;
						color: #999999;
						line-height: 1;
						margin-left: 12upx;
					}
				}
			}

		}

		map {
			margin-top: 50upx;
			width: 750upx;
			position: relative;
		}
		.map {
			width: 100%;
			height: 500upx;
			position: relative;
		}
		.controls {
			background: #FFF;
			width: calc(100% - 48upx);
			height: 200upx;
			left: 24upx;
			top: 24upx;
			position: absolute;
			z-index: 4;
			box-shadow:0px 0px 4px 1px rgba(0, 0, 0, 0.1);

		}

		.controls-title {
			position: absolute;
			top: 31upx;
			left: 25upx;
			font-size: 28upx;
			line-height: 1;
			color: #333333;
			z-index: 5;
		}

		.controls-content {
			position: absolute;
			width: 600upx;
			height: 90upx;
			top: 89upx;
			left: 25upx;
			z-index: 10;
			font-size: 28upx;
			color: #333333;
			word-break: break-all;
			word-wrap: break-word;
			white-space: pre-line;
		}

		.controls-img {
			width: 22upx;
			height: 22upx;
			position: absolute;
			right: 34upx;
			top: 79upx;
			z-index: 5;
		}

		.hotel_back {
			position: absolute;
			right: 24upx;
			top: 30upx;
			height: 22upx;
			width: 22upx;

			image {
				width: 22upx;
				height: 22upx;
			}

		}

	}

	.grab-details>.grab_button {

		height: 98upx;
		margin-bottom: 46upx;

		.grab_button_fixed {
			position: fixed;
			width: 100%;
			height: 98upx;
			bottom: 0;
			left: 0;
			z-index: 9999999;
			background: #fff;

			.grab_button_btn {
				width: 540upx;
				height: 90upx;
				margin: 0 auto;
				margin-top: 4upx;
				text-align: center;
				color: #FFF;
				line-height: 90upx;
				font-size: 32upx;
				background-color: #3595f9;
				border-radius: 8upx;
			}
		}
	}
</style>
